import isString from "lodash/isString";

const localeKey = "e9_locale";
const constant = {
  langRegP: /(~`~`(([\d ]{1,2}[^`]{0,2000}?`~`)+[\d ]{1,2}[^`]{0,2000}?)`~`~).{0,2000}?/i,
  blank: /&nbsp;/g,
  LANG_CONTENT_PREFIX: "~`~`",
  LANG_CONTENT_SPLITTER1: "`~`",
  LANG_CONTENT_SUFFIX: "`~`~",
  LANG_INPUT_PREFIX: "__multilangpre_"
};

const getUserLanguage = () => {
  if (localStorage.login) {
    try {
      const login = JSON.parse(localStorage.login);
      if (login.langId) {
        return login.langId;
      }
      if (window[localeKey]) {
        return window[localeKey].userLanguage || 7;
      }
    } catch (error) {
      console && console.error("多语言获取失败 :(", error);
    }
  }
};

const transLang = (str, lang) => {
  //如果没有设过相应语言的翻译，返回中翻译作为默认值
  let isExsit = false,
    defaultValue = "",
    oriLang = lang;
  if (lang.length < 2) lang += " ";
  str = str.replace(constant.blank, " ");
  let from = str.indexOf(constant.LANG_CONTENT_PREFIX),
    to = str.lastIndexOf(constant.LANG_CONTENT_SUFFIX);
  if (from !== -1 && to !== -1 && from + 4 < to) {
    let ls = str.substring(from + 4, to).split(constant.LANG_CONTENT_SPLITTER1);
    for (let i = 0; i < ls.length; i++) {
      let lg = ls[i];
      if (lg.indexOf("7 ") === 0) {
        defaultValue = lg.substring(lang.length);
      }
      if (lg.indexOf(lang) === 0) {
        isExsit = true;
        return lg.substring(lang.length);
      } else if (lg.startsWith(oriLang)) {
        isExsit = true;
        return lg.substring(oriLang.length);
      }
    }
  }
  if (!isExsit) {
    return defaultValue;
  }
  return str;
};

export const formatMultiLang = str => {
  if (!str || !isString(str) || str.indexOf(constant.LANG_CONTENT_PREFIX) < 0) {
    return str;
  }
  let lang = new String(getUserLanguage());
  let arr = null;
  while ((arr = str.match(constant.langRegP))) {
    let formatValue = arr[1];
    let value = transLang(formatValue, lang);
    str = str.replace(formatValue, value);
  }
  return str;
};